package com.engine.devcom.mode.util;

import com.engine.devcom.mode.entity.BaseRestConfigDto;
import com.engine.devcom.mode.entity.BaseRestDtConfigDto;
import com.weaver.formmodel.util.DateHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : hmy
 * @since : 2025/5/6
 */
public class BaseRestConfigUtils {

    /**
     * 获取接口配置信息
     *
     * @param interfaceKey
     * @return
     */
    public static BaseRestConfigDto getBaseRestConfigDto(String interfaceKey) {
        if (StringUtils.isBlank(interfaceKey)) {
            return null;
        }
        RecordSet rs = new RecordSet();
        rs.executeQuery("select cxsql, id, tag  from uf_interfacebasecfg where tag = ?", interfaceKey);
        BaseRestConfigDto baseRestConfigDto = new BaseRestConfigDto();
        if (rs.next()) {
            baseRestConfigDto.setId(rs.getString("id"));
            baseRestConfigDto.setSql(rs.getString("cxsql"));
            baseRestConfigDto.setTag(rs.getString("tag"));
        } else {
            return null;
        }

        if (!StringUtils.isBlank(baseRestConfigDto.getId())) {
            rs.executeQuery("select sqlyszd, qqcsm from uf_interfacebasecfg_dt1 where mainid = ?",
                    baseRestConfigDto.getId());
            List<BaseRestDtConfigDto> paramMapping = new ArrayList<>();
            while (rs.next()) {
                BaseRestDtConfigDto baseRestDtConfigDto = new BaseRestDtConfigDto();
                baseRestDtConfigDto.setSqlFieldName(rs.getString("sqlyszd"));
                baseRestDtConfigDto.setParamFieldName(rs.getString("qqcsm"));
                paramMapping.add(baseRestDtConfigDto);

            }
            baseRestConfigDto.setParamMapping(paramMapping);
        }

        return baseRestConfigDto;
    }


    /**
     * 替换sql参数
     *
     * @param dto
     * @param reqParams
     * @param user
     * @return
     */
    public static String replaceSqlParams(BaseRestConfigDto dto, Map<String, Object> reqParams, User user) {
        RecordSet rs = new RecordSet();
        String sql = dto.getSql();

        sql = sql.replaceAll("\\$currentdate\\$", DateHelper.getCurrentDate());
        sql = sql.replaceAll("\\$currentdept\\$", user.getUserDepartment() + "");
        sql = sql.replaceAll("\\$currentuser\\$", user.getUID() + "");

        // 替换自定义参数
        List<BaseRestDtConfigDto> paramMapping = dto.getParamMapping();
        if (!CollectionUtils.isEmpty(paramMapping)) {
            for (BaseRestDtConfigDto baseRestDtConfigDto : paramMapping) {
                sql = sql.replaceAll("\\$" + baseRestDtConfigDto.getSqlFieldName() + "\\$",
                        Util.null2String(reqParams.getOrDefault(baseRestDtConfigDto.getParamFieldName(), "")));
            }
        }
        return sql;
    }

}
